import httpFetch from "share/httpFetch";
import errorMessage from "share/errorMessage";
import React from "react";
import { deepCopy, messages } from "share/common";
import moment from "moment";
import exampleData from "containers/home/home.example.constant";

function handleExample(key, params) {
  const example = exampleData[key];
  const result = {};
  const dataArr = [];
  const queryMonth = moment(`${params.year}-${params.month}`).format("YYYY-MM");
  for (let i = 0; i < 12; i++) {
    dataArr.unshift(moment().subtract(i, "months").format("YYYY-MM"));
  }
  const queryIndex = dataArr.indexOf(queryMonth);
  Object.keys(example.array).forEach((keyName) => {
    result[keyName] = example.array[keyName].map((value, index) => {
      return {
        year: Number(dataArr[index].split("-")[0]),
        month: Number(dataArr[index].split("-")[1]),
        monthOfYear: dataArr[index],
        totalAmount: value,
      };
    });
  });
  Object.keys(example.stringData).forEach((keyName) => {
    result[keyName] = example.stringData[keyName]
      ? example.stringData[keyName]
      : result.amountList[queryIndex].totalAmount;
  });
  Object.keys(example.knownData).forEach((keyName) => {
    result[keyName] =
      keyName === "paidTotalAmount" ? result.paidAmountList[queryIndex] : result.payingAmountList[queryIndex];
  });
  result.monthlyExpenseOverviewList = example.feesDetailArray[queryIndex].data;
  return new Promise((resolve) => {
    resolve({ data: result, status: 200 });
  });
}

const COLOR_LIST = ["#4B8DFF", "#50C0FF", "#FFC80A", "#32CD91"];

const filterMoney = React.Component.prototype.filterMoney;

function personalSeriesData(data) {
  const result = [[], [], []];
  result[0] = data.paidAmountList.map((item, index) => {
    const result = {
      totalValue: data.amountList[index].totalAmount,
      value: item.totalAmount,
      name: item.monthOfYear,
      paid: messages("basic-1.key227", {
        arg1: `<span class="value-text">${filterMoney(data.paidAmountList[index].totalAmount, 2, true)}</span>`,
      }) /*已付款：{arg1}*/,
      paying: messages("basic-1.key228", {
        arg1: `<span class="value-text">${filterMoney(data.payingAmountList[index].totalAmount, 2, true)}</span>`,
      }) /*未付款：{arg1}*/,
      isActive: index === 11 ? "Y" : "N",
      itemStyle: {
        color: index === 11 ? "#4B8DFF" : "#98BEFF",
        barBorderRadius: data.payingAmountList[index].totalAmount ? [0, 0, 0, 0] : [9999, 9999, 0, 0],
      },
    };
    return result;
  });
  result[1] = data.payingAmountList.map((item, index) => {
    const result = {
      value: item.totalAmount,
      name: item.monthOfYear,
      paid: messages("basic-1.key227", {
        arg1: `<span class="value-text">${filterMoney(data.paidAmountList[index].totalAmount, 2, true)}</span>`,
      }) /*已付款：{arg1}*/,
      paying: messages("basic-1.key228", {
        arg1: `<span class="value-text">${filterMoney(data.payingAmountList[index].totalAmount, 2, true)}</span>`,
      }) /*未付款：{arg1}*/,
      isActive: index === 11 ? "Y" : "N",
      itemStyle: {
        color: index === 11 ? "#50C0FF" : "#8FD6FF",
        barBorderRadius: [9999, 9999, 0, 0],
      },
    };
    return result;
  });
  return result;
}

function deptSeriesData(data) {
  return data.amountList.map((item, index) => {
    const result = {
      value: item.totalAmount,
      name: item.monthOfYear,
      isActive: index === 11 ? "Y" : "N",
      itemStyle: { color: index === 11 ? "#4B8DFF" : "#98BEFF" },
    };
    return result;
  });
}

const typeFuncMap = {
  personalReportShow: personalSeriesData,
  departmentReportShow: deptSeriesData,
  costCenterReportShow: deptSeriesData,
};

export default {
  //获取报表权限
  getPrivilege(params) {
    return httpFetch.get(`/api/account/privilege`, params).catch((err) => {
      errorMessage(err.response);
    });
  },
  //获取全年报销情况
  getAllYearData(params, type = "personalReportShow", exampleMode) {
    if (exampleMode) return handleExample("dashboardReportData", params);
    const map = {
      personalReportShow: "/api/personal/expense/report/overview",
      departmentReportShow: "/api/personal/department/overview",
      costCenterReportShow: "/api/personal/costCenter/overview",
    };
    return httpFetch.get(map[type], params).catch((err) => {
      errorMessage(err.response);
    });
  },

  createBarOptions({ data, currency, type }) {
    const xAxisData = data.amountList.map((item) => {
      return messages("basic-1.key229", { arg1: item.month }) /*{arg1}月*/;
    });
    const seriesData = typeFuncMap[type](data);
    let seriesDataArray;
    if (type === "personalReportShow") {
      seriesDataArray = [
        {
          name: messages("basic-1.key214") /*本月已报销金额*/,
          type: "bar",
          barWidth: 12,
          barGap: "50%",
          data: seriesData[0],
          label: {
            normal: {
              show: false,
            },
          },
          stack: "add",
          // emphasis: { itemStyle: { color: COLOR_LIST_HOME_HOVER[index % 4] } },
        },
        {
          name: messages("basic-1.key214") /*本月已报销金额*/,
          type: "bar",
          barWidth: 12,
          barGap: "50%",
          data: seriesData[1],
          label: {
            normal: {
              show: false,
            },
          },
          stack: "add",
          // emphasis: { itemStyle: { color: COLOR_LIST_HOME_HOVER[index % 4] } },
        },
      ];
    } else {
      seriesDataArray = [
        {
          name: messages("basic-1.key215") /*报销总额*/,
          type: "bar",
          barWidth: 12,
          barGap: "50%",
          data: seriesData,
          itemStyle: {
            barBorderRadius: [9999, 9999, 0, 0],
          },
          label: {
            normal: {
              show: false,
            },
          },
          // emphasis: { itemStyle: { color: COLOR_LIST_HOME_HOVER[index % 4] } },
        },
      ];
    }
    return {
      legend: {
        show: false,
      },
      tooltip: {
        appendToBody: true,
        extraCssText: "box-shadow: 0 4px 12px 0 rgba(0,0,0,0.10);",
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
        textStyle: {
          fontSize: 10,
          color: "#4E5B71",
        },
        backgroundColor: "#FFF",
        padding: 12,
        formatter:
          type === "personalReportShow"
            ? (item) => {
                const realYear = item[0].data.name;
                const year = messages("basic-1.key297", {
                  arg1: moment(realYear).format("YYYY"),
                  arg2: moment(realYear).format("MM"),
                }); /*{arg1}年{arg2}月*/
                return `<div class="dashboard-report-tooltip"><div class="year-title">${year}</div>
<div class="single-value">${item[0].seriesName}：<span class="value-text">${filterMoney(
                  item[0].data.totalValue,
                  2,
                  true
                )}</span></div>
<div class="single-value">
<span class="dot" style="background: ${item[0].color};"></span>${
                  item[0].data.paid
                }&nbsp;&nbsp;&nbsp;<span class="dot" style="background: ${item[1].color};"></span>${item[0].data.paying}
</div>
</div>`;
              }
            : (item) => {
                const realYear = item[0].data.name;
                const year = messages("basic-1.key297", {
                  arg1: moment(realYear).format("YYYY"),
                  arg2: moment(realYear).format("MM"),
                }); /*{arg1}年{arg2}月*/
                return `<div class="dashboard-report-tooltip"><div class="year-title">${year}</div>${item.map(
                  (single) => {
                    return `<div class="single-value"><span class="dot" style="background: ${single.color};"></span>${
                      item[0].seriesName
                    }：<span class="value-text">${filterMoney(single.data.value, 2, true)}</span></div>`;
                  }
                )}</div>`;
              },
      },
      grid: { top: "30px", left: "5px", right: "5px", bottom: "10px", containLabel: true },
      xAxis: [
        {
          data: xAxisData,
          inverse: false,
          axisLine: {
            lineStyle: {
              color: "#DBE6F3",
            },
          },
          axisTick: {
            show: false,
          },
          axisPointer: {
            shadowStyle: {
              color: "rgba(31,112,252,0.1)",
            },
          },
          axisLabel: {
            interval: 0,
            fontSize: 10,
          },
        },
      ],
      yAxis: [
        {
          name: messages("basic-1.key230", { arg1: currency }) /*金额({arg1})*/,
          nameTextStyle: {
            align: "left",
            color: "#b5c0ce",
          },
          type: "value",
          boundaryGap: ["0", "15%"], // 右侧留白用于显示label
          splitLine: {
            lineStyle: {
              type: "dashed",
              color: "#EBF0F5",
            },
          },
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: {
            interval: 0,
            margin: 10,
            color: "#B5C0CE",
            fontSize: 12,
          },
        },
      ],
      series: seriesDataArray,
      color: COLOR_LIST,
    };
  },
};
